import React, { Component } from 'react';
import {
  StyleSheet, View, ScrollView, DeviceEventEmitter, TouchableWithoutFeedback, TouchableOpacity, Image, Alert,
} from 'react-native';
import { Text } from 'native-base';
import { produce } from 'immer';
import ZlstIcon from '../../../../components/zlst-icons';
import Theme from '../../../../native-base-theme/variables/commonColor';
import { UtilToast } from '../../../../utils/util-method';
import * as sparePartService from '../../../../services/sparePart';
import * as todoService from '../../../../services/todo';
import { FormTextChoice, FormText, FormSearchChoiceChange, FormInputPop } from '../../../../components';
import Item from './item';

class NewOutBound extends Component {
  static navigationOptions = {
    title: '新增出库',
    headerStyle: { backgroundColor: Theme.toolbarDefaultBg, borderBottomWidth: 0, elevation: 0 },
    headerTintColor: '#FFFFFF',
    headerTitleStyle: {
      fontWeight: 'bold',
      fontSize: 20,
      flex: 1,
      textAlign: 'center',
    },
    headerBackImage: (
      <ZlstIcon
        name="fanhui"
        size={24}
        color="white"
      />
    ),
    headerRight: <View />,
  }

  searchUri = '127.0.0.1';

  searHeaderTitle = '请选择';

  searchNoHeader = false;

  _choiceConfirm = null;

  extraInfo = {};

  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      modalInputVisible: false,
      outBound: { id: '', name: '出库仓库', value: '' },
      llr: { id: '', name: '领料人', value: '' },
      lldw: { id: '', name: '领料单位', value: '' },
      destination: { id: '', name: '发往仓库', value: '' },
      datas: [],
    };
  }

  // 初始化
  componentDidMount() {
    this.setState(produce(draft => {
      draft.llr.id = global.user.staff.id;
      draft.llr.value = global.user.staff.name;
      draft.lldw.id = global.user.organization.id;
      draft.lldw.value = global.user.organization.name;
    }));
    DeviceEventEmitter.addListener('addPartEvent', this.addPartEvent);
    this.getInitOutBound();
  }

  componentWillUnmount() {
    DeviceEventEmitter.removeAllListeners('addPartEvent');
  }

  addPartEvent = (v) => {
    // const t = { id: '002', materId: '002', name: '散热片' };
    // if (this.state.datas.length > 0) {
    //   alert('只能选择一个备件，请先删除');
    // } else {
    //   this.getMaterialDefinition(v);
    //   // this.addPart(t);
    // }
    this.getMaterialDefinition(v);
  }

  _toMianPage = () => {
    if (this.props.navigation) {
      this.props.navigation.goBack();
    } else {
      DeviceEventEmitter.emit('swiperIncidentPageEvent', -1);
    }
  }

  _cancelInputModal = () => {
    this.setState({ modalInputVisible: false });
  }

  _showInputModal = () => {
    this.setState({
      modalInputVisible: true,
    });
  }

  _cancelModal = () => {
    this.setState({ modalVisible: false });
  }

  _showModal = () => {
    this.setState({
      modalVisible: true,
    });
  }

  choiceOutBound = () => {
    this._choiceConfirm = (it) => {
      this.setState(produce(draft => {
        draft.outBound.id = it[0].id;
        draft.outBound.value = it[0].name;
      }));
    };
    this.searchUri = `${sparePartService.serverName}/infoWarehouse/topHouse`;
    // this.searchUri = 'http://192.168.15.56:80/infoWarehouse/topHouse';
    this.searchNoHeader = true;
    this.searHeaderTitle = '请选择出库仓库';
    this.extraInfo = {};
    this._showModal();
  }

  choiceLlr = () => {
    this._choiceConfirm = (it) => {
      this.setState(produce(draft => {
        draft.llr.id = it[0].id;
        draft.llr.value = it[0].name;
        draft.lldw.id = it[0].orgId;
        draft.lldw.value = it[0].orgName;
        draft.destination.id = '';
        draft.destination.value = '';
      }));
    };
    // this.searchUri = `${sparePartService.serverName}/stockLogCtrl/staff`;
    this.searchUri = '/api-ms/system/staffs/search';
    this.searHeaderTitle = '请选择领料人';
    this.searchNoHeader = false;
    this.extraInfo = {};
    this._showModal();
  }

  choiceDestination = () => {
    if (this.state.llr.id == '') {
      UtilToast('请先选择领料人', 'danger');
    } else {
      this._choiceConfirm = (it) => {
        this.setState(produce(draft => {
          draft.destination.id = it[0].id;
          draft.destination.value = it[0].name;
        }));
      };
      this.searchUri = `${sparePartService.serverName}/stockLogCtrl/toWarehouse`;
      // this.searchUri = 'http://192.168.15.56:80/stockLogCtrl/toWarehouse';
      this.searHeaderTitle = '请选择发往仓库';
      this.searchNoHeader = true;
      this.extraInfo = { condition: this.state.llr.id };
      this._showModal();
    }
  }

  toQrcode = () => {
    global.navigation.navigate({ routeName: 'Qrcode', params: { flag: 'addPartEvent' } });
  }

  add = () => {
    // const t = { id: '001', materId: '001', name: 'cpu' };
    // this.addPart(t);
    this._showInputModal();
  }

  addPart = (t) => {
    // const t = { materialName: '002', materialCode1: '散热片', materialSpecModel: '散热片', supplierName: '散热片', minPackageUnit: '散热片', lotCode: '散热片' };
    let flag = false; // 表示是否有过该批次物料
    this.state.datas.forEach((data, index) => {
      if (data.materialCode1 == t.materialCode1) {
        flag = true;
        let check = true; // 检测是否没有添加过该物料批次
        data.pc.forEach((mdata) => {
          if (mdata.name == t.lotCode) {
            check = false;
          }
        });

        if (check) {
          this.setState(produce(draft => {
            const mdata = { id: '', name: t.lotCode, materialLotId: t.materialLotId, allNum: t.usableQty, num: '1', splitFlag: false };
            draft.datas[index].pc.push(mdata);
          }));
        } else {
          UtilToast('已经添加过该物料批次', 'danger');
        }
      }
    });

    if (!flag) {
      if (this.state.datas.length == 0) {
        this.setState(produce(draft => {
          // const mdata = { materialName: t.materialName, materialCode1: t.materialCode1, materialSpecModel: t.materialSpecModel, supplierName: t.supplierName, minPackageUnit: t.minPackageUnit, lotCode: t.lotCode, pc: [{ id: '', name: t.lotCode, materialLotId: t.materialLotId }] };
          // const showSplitBtn = t.packageUnit !== t.consumeUnit;
          const showSplitBtn = true;
          const mdata = { ...t, showSplitBtn, pc: [{ id: '', name: t.lotCode, materialLotId: t.materialLotId, allNum: t.usableQty, num: '1', splitFlag: false }] };

          // draft.datas.push(mdata);
          draft.datas.splice(0, 0, mdata);
        }));
      } else {
        UtilToast('只能添加一类物料', 'danger');
      }
    }
  }

  del = (index, mindex) => {
    if (this.state.datas[index].pc.length > 1) {
      this.setState(produce(draft => {
        draft.datas[index].pc.splice(mindex, 1);
      }));
    } else {
      this.setState(produce(draft => {
        draft.datas.splice(index, 1);
      }));
    }
  }

  _onChangeText = (index, mindex, text) => {
    this.setState(produce(draft => {
      const newText = text.replace(/[^\d]+/, '');
      draft.datas[index].pc[mindex].num = newText;
    }));
  }

  onCheckChange = (index, mindex, splitFlag) => {
    this.setState(produce(draft => {
      draft.datas[index].pc[mindex].splitFlag = splitFlag;
    }));
  }

  confirmSub = () => {
    if (this.state.outBound.value == '') {
      UtilToast('请选择出库仓库', 'danger');
    } else if (this.state.llr.id == '') {
      UtilToast('请选择领料人', 'danger');
    } else if (this.state.destination.value == '') {
      UtilToast('请选择发往仓库', 'danger');
    } else if (this.state.datas.length == 0 ) {
      UtilToast('请添加一个物料批次', 'danger');
    } else {
      let flag = true;
      if (this.state.datas[0].showSplitBtn) {
        for (let i = 0; i < this.state.datas[0].pc.length; i++) {
          if (this.state.datas[0].pc[i].splitFlag) {
            if (!this.state.datas[0].pc[i].num) {
              flag = false;
              UtilToast(`请输入物料批次${this.state.datas[0].pc[i].name}拆分数目`, 'danger');
            } else if (this.state.datas[0].pc[i].num == 0) {
              flag = false;
              UtilToast(`物料批次${this.state.datas[0].pc[i].name},拆分数目不能为0`, 'danger');
              break;
            } else if (parseInt(this.state.datas[0].pc[i].num) > parseInt(this.state.datas[0].pc[i].allNum)) {
              flag = false;
              UtilToast(`物料批次${this.state.datas[0].pc[i].name},拆分数目不能大于库存量`, 'danger');
              break;
            }
          }
        }
      }

      if (flag) {
        Alert.alert(
          '提示',
          '确定提交',
          [
            { text: '取消', style: 'cancel' },
            {
              text: '确定',
              onPress: () => {
                this.submit();
              },
            },
          ],
        );
      }
    }
  }

  onSearch = (v) => {
    this.setState({ modalInputVisible: false });
    // const t = { id: '002', materId: '002', name: '散热片' };
    // if (this.state.datas.length > 0) {
    //   alert('只能选择一个备件，请先删除');
    // } else {
    //   // this.addPart(t);
    //   this.getMaterialDefinition(v);
    // }
    this.getMaterialDefinition(v);
    // const t = { materialName: '002', materialCode1: '散热片', materialSpecModel: '散热片', supplierName: '散热片', minPackageUnit: '散热片', lotCode: '散热片' };
  }

  getMaterialDefinition = async (lotCode) => {
    try {
      DeviceEventEmitter.emit('showLoading', true);
      const data = await sparePartService.queryMaterialDefinitionByLotCode({ lotCode });
      DeviceEventEmitter.emit('showLoading', false);
      if (data) {
        this.addPart(data);
      }
    } catch (e) {
      console.log(e);
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  getInitOutBound = async () => {
    try {
      DeviceEventEmitter.emit('showLoading', true);
      const { list } = await todoService.choiceSearch({ condition: '', page: 1 }, `${sparePartService.serverName}/infoWarehouse/topHouse`);
      DeviceEventEmitter.emit('showLoading', false);
      if (list && list.length > 0) {
        this.setState(produce(draft => {
          draft.outBound.id = list[0].id;
          draft.outBound.value = list[0].name;
        }));
      } else {
        UtilToast('没有一级仓库', 'danger');
      }
    } catch (e) {
      console.log(e);
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  submit = async () => {
    try {
      const lotCodes = [];
      const materialLotIds = [];
      const materialLotList = [];
      this.state.datas[0].pc.forEach((data, index) => {
        lotCodes.push(data.name);
        materialLotIds.push(data.materialLotId);
        const materialLot = { lotCode: data.name, materialLotId: data.materialLotId, outWarehouseType: `${data.splitFlag && data.num !== data.allNum ? '1' : '0'}`, number: data.num };
        materialLotList.push(materialLot);
      });

      DeviceEventEmitter.emit('showLoading', true);
      const params = {
        stockLogType: null,
        relatedBillType: null,
        materialId: this.state.datas[0].materialId,
        materialName: this.state.datas[0].materialName,
        materialCode: this.state.datas[0].materialCode1,
        gradeCode: null,
        warehouseName: this.state.outBound.value,
        externalBillType: null,
        catchedBy: this.state.llr.id,
        catchedName: this.state.llr.value,
        catchedRole: this.state.lldw.value,
        packageUnit: this.state.datas[0].packageUnit,
        packageQty: this.state.datas[0].packageQty,
        locatorId: this.state.datas[0].locatorId,
        consumeUnit: this.state.datas[0].consumeUnit,
        consumeQty: this.state.datas[0].consumeQty,
        toWarehouseName: this.state.destination.value,
        materialLotList,
        catchedOrgId: this.state.lldw.id,
        supplierId: this.state.datas[0].supplierId,
        supplierName: this.state.datas[0].supplierName,
        manufacturerId: null,
        manufacturerName: null,
      };
      const data = await sparePartService.subOutBound(params);
      DeviceEventEmitter.emit('showLoading', false);
      if (data) {
        UtilToast('新增出库成功', 'success');
        this.props.navigation.goBack();
        DeviceEventEmitter.emit('refreshPageEvent');
      }
    } catch (e) {
      console.log(e);
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  render() {
    return (
      <View style={styles.container}>
        {this.state.modalVisible && (
          <FormSearchChoiceChange
            onClose={this._cancelModal}
            searchUri={this.searchUri}
            extraInfo={this.extraInfo}
            type="radio"
            title={this.searHeaderTitle}
            searchNoHeader={this.searchNoHeader}
            choiceConfirm={this._choiceConfirm}
          />
        )}
        <FormInputPop
          modalVisible={this.state.modalInputVisible}
          onClose={this._cancelInputModal}
          placeholder="请输入备件批次码"
          keyboardType="default"
          onSearch={this.onSearch}
          btnText="添加"
          numberOfLines={1}
        />
        <ScrollView style={{ flex: 1 }}>
          <View>
            <View style={styles.title_container}><FormText name="基础信息" fontColor="black" /></View>
            <FormTextChoice name={this.state.outBound.name} value={this.state.outBound.value} choiceMethod={this.choiceOutBound} />
            <FormTextChoice name={this.state.llr.name} value={this.state.llr.value} choiceMethod={this.choiceLlr} />
            <FormText name={this.state.lldw.name} value={this.state.lldw.value} />
            <FormTextChoice name={this.state.destination.name} value={this.state.destination.value} choiceMethod={this.choiceDestination} />
            <View style={styles.itemContainer}>
              <View style={styles.itemLeftContainer}>
                <Text style={styles.fontStyle}>物料清单</Text>
              </View>
              <View style={styles.itemRightContainer}>
                <ZlstIcon
                  onPress={this.toQrcode}
                  name="saoma"
                  size={22}
                  color="black"
                  style={{ marginRight: 20 }}
                />
                <TouchableWithoutFeedback onPress={() => this.add()}>
                  <Text style={styles.fontStyle}>添加</Text>
                </TouchableWithoutFeedback>
              </View>
            </View>
            <Item datas={this.state.datas} del={this.del} onCheckChange={this.onCheckChange} _onChangeText={this._onChangeText} />
          </View>
        </ScrollView>
        <TouchableOpacity style={styles.footer} onPress={() => this.confirmSub()} activeOpacity={0.8}>
          <Image
            source={require('../../../../../assets/images/btn-cut-line-xxx.png')}
            style={{ width: '100%', height: 2, alignItems: 'center' }}
            resizeMode="stretch"
            resizeMethod="auto"
          />
          <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Text style={{ color: 'white' }}>提交</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: '100%',
    flexDirection: 'column',
    backgroundColor: Theme.myPrimary,
  },
  title_container: {
    width: '100%',
    backgroundColor: 'white',
    borderLeftWidth: 8,
    borderLeftColor: '#4f6fe3',
    // borderRadius: 4,
  },
  header_container: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
  },
  headerText: {
    color: 'white',
    fontWeight: 'bold',
  },
  backBtn: {
    paddingLeft: 8,
    paddingRight: 8,
    paddingTop: 16,
    paddingBottom: 16,
  },
  itemContainer: {
    padding: 8,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'white',
    borderLeftWidth: 8,
    borderLeftColor: '#4f6fe3',
  },
  itemLeftContainer: {
    flex: 1,
  },
  itemRightContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-end',
  },
  fontStyle: {
    fontSize: Theme.myNormalFontSize,
    color: 'black',
  },
  footer: {
    width: '100%',
    flexDirection: 'column',
    backgroundColor: Theme.myPrimary,
    height: 48,
  },
});

export default NewOutBound;
